package com.cy.chatTest.controller;

import com.cy.chatTest.bin.BaseEntity;
import com.cy.chatTest.common.CommonUtil;
import com.cy.chatTest.common.StringUtils;
import com.cy.chatTest.db.UserInfo;
import com.cy.chatTest.db.UserInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/login")
public class Login {
    @Autowired
    UserInfoRepository userInfoRepository;


    private Map toLoginInfo(UserInfo userInfo,HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
        String cookie = UUID.randomUUID().toString();
        userInfo.setCookie(cookie);
        userInfo.setCookieValidity(System.currentTimeMillis() + 24L * 60L * 60L * 1000L);
        userInfo.setIp(CommonUtil.getIPAddress(httpServletRequest));
        userInfoRepository.save(userInfo);
        httpServletResponse.addCookie(new Cookie("ChatApp", cookie));
        Map hashMap = new HashMap<String,Object>();
        hashMap.put("token",userInfo.getToken());
        hashMap.put("user",userInfo);
        return hashMap;
    }

    @PostMapping("/login")
    @ResponseBody
    public BaseEntity login(String email, String passwordOrToken, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        UserInfo userInfo = userInfoRepository.findByUsername(email);

        if (userInfo != null) {
            if (userInfo.getPassword().equals(passwordOrToken)) {
                userInfo.setToken(UUID.randomUUID().toString());
                return new BaseEntity(true, toLoginInfo(userInfo,httpServletRequest,httpServletResponse));
            } else if (userInfo.getToken().equals(passwordOrToken)) {
                if (!StringUtils.isEmpty(userInfo.getCookie())
                        && userInfo.getCookie().equals(CommonUtil.getCookie(httpServletRequest, "ChatApp"))
                        && System.currentTimeMillis() < userInfo.getCookieValidity()
                        ) {
                    return new BaseEntity(true, toLoginInfo(userInfo,httpServletRequest,httpServletResponse));
                } else {
                    return new BaseEntity(false, "登录失效");
                }

            } else {
                return new BaseEntity(false, "登录失败");
            }
        } else {
            return new BaseEntity(false, "用户名或密码错误");
        }
    }


    @GetMapping(value = "/test")
    public String ppa() {
        return "test";
    }
}
